import axios, { InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios'
import JSONbig from 'json-bigint'//解决超过 16 位数字精度丢失问题
const service = axios.create({
  transformResponse: [ function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      //  JSONbig.parse(data)
      return JSON.parse(JSON.stringify(JSONbig.parse(data)))
    } catch (err) {
      // 如果转换失败，则包装为统一数据格式并返回
      return {
        data
      }
    }
  } ]
})

service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

const request = async <T = any>(config: AxiosRequestConfig): Promise<Api.Result<T>> => {
  try {
    const { data } = await service.request<Api.Result<T>>(config)
    if (data.code !== 200) {
      console.log('data.code !== 200', data.message)
    }
    return data
  } catch (err: any) {
    const { status, message } = err.response
    if (status === 401) {
      console.log('401')
    } else if (status === 403) {
      console.log('403')
    }
    return {
      code: -1,
      message,
      data: null as any,
      result: null as any
    }
  }
}

export default request